<template>
  <!--公司风险分析-->
  <v-card>
    <div class="analysis">
      <p class="infoTitle">
        {{ $t("assessment.RiskAnalysisOfRelevantCompanies") }}
      </p>
      <!--tree-->
      <div class="body">
        <div class="analysisBox">
          <div class="analysisChart" ref="analysisChart"></div>
          <div :class="['nothing', { show: hasSomeThing }]">
            {{ $t("assessment.NoDataAvailable") }}
          </div>
        </div>
        <div class="tips">
          <span v-for="(item, index) in tips" :key="index">{{ item }}</span>
        </div>
      </div>
    </div>
  </v-card>
</template>

<script>
export default {
  data() {
    return {
      companyName: this.$cookie.get("companyName") || "", //公司名称
      analysisChart: null,
      analysisOption: null,
      tips: [
        this.$t("assessment.RiskyCompanies"),
        this.$t("assessment.RiskFreeCompanies"),
      ],
      chartData: [],
      chartLinks: [],
      hasSomeThing: false,
    };
  },
  methods: {
    init() {
      this.analysisChart = this.$echarts.init(this.$refs.analysisChart);
    },
    //获取风控分析数据
    getAnalysis() {
      this.analysisChart.showLoading();
      let companyName = this.companyName;
      this.$post(this.$Url.riskInfo.riskAnalysis, {
        eid: localStorage.getItem("eid") || "",
      }).then((res) => {
          if (res.status == 200 && res.data) {
            let message = res.data.message;
            if (message.length <= 0) {
              this.hasSomeThing = true;
              this.analysisChart.hideLoading();
              return;
            }
            var getData = message[0];
            var imgs =
              "image://" +
              "";
            var imgsBlueBig =
              "image://" +
              "";
            var imgsBlueLittle =
              "image://" +
              "";
            var imgs02 =
              "image://" +
              "";
            var imgsRedBig =
              "image://" +
              "";
            var imgsRedLittle =
              "image://" +
              "";
            var list = [
              {
                name: companyName,
                category: 0,
                proportion: parseFloat(getData.score).toFixed(5) || 100,

                entcoremambers_dict: getData.entcoremambers_dict.message, //核心人失信
                execution: getData.execution.message, //企业失信
                overduetax: getData.overduetax.message, //历史欠税
                case_mes: getData.case_mes.message, //违法违规
                equityqualities: getData.equityqualities.message, //股权出资
                judicialfreeze: getData.judicialfreeze.message, //股权冻结
                auctions: getData.auctions.message, //司法拍卖
                business_error: getData.business_error && getData.business_error.message, // business_error

                sname: companyName,
                // 中央圆
                symbol: parseFloat(getData.score) > 5 ? imgsRedBig : imgs,
              },
            ];
            //子级
            if (getData.c_items && getData.c_items.length > 0) {
              for (let i = 0; i < getData.c_items.length; i++) {
                let child = {
                  isFather: false,
                  name: getData.c_items[i].name,
                  category: 1,
                  proportion: parseFloat(getData.c_items[i].score).toFixed(5),
                  sname: companyName,

                  entcoremambers_dict:
                    getData.c_items[i].entcoremambers_dict.message, //核心人失信
                  execution: getData.c_items[i].execution.message, //企业失信
                  overduetax: getData.c_items[i].overduetax.message, //历史欠税
                  case_mes: getData.c_items[i].case_mes.message, //违法违规
                  equityqualities: getData.c_items[i].equityqualities.message, //股权出资
                  judicialfreeze: getData.c_items[i].judicialfreeze.message, //股权冻结
                  auctions: getData.c_items[i].auctions.message, //司法拍卖
                  business_error: getData.c_items[i].business_error && getData.c_items[i].business_error.message, // business_error

                  symbol:
                    parseFloat(getData.c_items[i].score) > 1
                      ? parseFloat(getData.c_items[i].score) > 5
                        ? imgsRedBig
                        : imgsRedLittle
                      : parseFloat(getData.c_items[i].score) < 2
                      ? imgsBlueBig
                      : imgsBlueLittle,
                };
                list.push(child);
                if (
                  getData.c_items[i].c_items &&
                  getData.c_items[i].c_items.length > 0
                ) {
                  for (let m = 0; m < getData.c_items[i].c_items.length; m++) {
                    let child1 = {
                      isFather: true,
                      name: getData.c_items[i].c_items[m].name,

                      entcoremambers_dict:
                        getData.c_items[i].c_items[m].entcoremambers_dict
                          .message, //核心人失信
                      execution:
                        getData.c_items[i].c_items[m].execution.message, //企业失信
                      overduetax:
                        getData.c_items[i].c_items[m].overduetax.message, //历史欠税
                      case_mes: getData.c_items[i].c_items[m].case_mes.message, //违法违规
                      equityqualities:
                        getData.c_items[i].c_items[m].equityqualities.message, //股权出资
                      judicialfreeze:
                        getData.c_items[i].c_items[m].judicialfreeze.message, //股权冻结
                      auctions: getData.c_items[i].c_items[m].auctions.message, //司法拍卖
                      business_error:
                        getData.c_items[i].c_items[m].business_error && c_items[i].c_items[m].business_error.message, // business_error

                      category: 2,
                      proportion: parseFloat(
                        getData.c_items[i].c_items[m].score
                      ).toFixed(5),
                      sname: getData.c_items[i].name,
                      symbol:
                        parseFloat(getData.c_items[i].c_items[m].score) > 1
                          ? parseFloat(getData.c_items[i].c_items[m].score) > 5
                            ? imgsRedBig
                            : imgsRedLittle
                          : parseFloat(getData.c_items[i].c_items[m].score) < 2
                          ? imgsBlueBig
                          : imgsBlueLittle,
                    };
                    list.push(child1);
                  }
                }
              }
            }
            //父级
            if (getData.p_items.length > 0) {
              for (let i = 0; i < getData.p_items.length; i++) {
                let listItem = {
                  isFather: true,
                  name: companyName,

                  entcoremambers_dict:
                    getData.p_items[i].entcoremambers_dict.message, //核心人失信
                  execution: getData.p_items[i].execution.message, //企业失信
                  overduetax: getData.p_items[i].overduetax.message, //历史欠税
                  case_mes: getData.p_items[i].case_mes.message, //违法违规
                  equityqualities: getData.p_items[i].equityqualities.message, //股权出资
                  judicialfreeze: getData.p_items[i].judicialfreeze.message, //股权冻结
                  auctions: getData.p_items[i].auctions.message, //司法拍卖
                  business_error: getData.p_items[i].business_error && getData.p_items[i].business_error.message, // business_error

                  category: 1,
                  proportion: parseFloat(getData.p_items[i].score).toFixed(5),
                  sname: getData.p_items[i].name,
                  symbol:
                    parseFloat(getData.p_items[i].score) > 1
                      ? parseFloat(getData.p_items[i].score) > 5
                        ? imgsRedBig
                        : imgsRedLittle
                      : parseFloat(getData.p_items[i].score) < 2
                      ? imgsBlueBig
                      : imgsBlueLittle,
                };
                list.push(listItem);
                if (getData.p_items[i].p_items.length > 0) {
                  for (let m = 0; m < getData.p_items[i].p_items.length; m++) {
                    let listItem1 = {
                      isFather: true,
                      name: getData.p_items[i].p_items[m].name,

                      entcoremambers_dict:
                        getData.p_items[i].p_items[m].entcoremambers_dict
                          .message, //核心人失信
                      execution:
                        getData.p_items[i].p_items[m].execution.message, //企业失信
                      overduetax:
                        getData.p_items[i].p_items[m].overduetax.message, //历史欠税
                      case_mes: getData.p_items[i].p_items[m].case_mes.message, //违法违规
                      equityqualities:
                        getData.p_items[i].p_items[m].equityqualities.message, //股权出资
                      judicialfreeze:
                        getData.p_items[i].p_items[m].judicialfreeze.message, //股权冻结
                      auctions: getData.p_items[i].p_items[m].auctions.message, //司法拍卖
                      business_error:getData.p_items[i].p_items[m].business_error && 
                        getData.p_items[i].p_items[m].business_error.message, // business_error

                      category: 2,
                      proportion: parseFloat(
                        getData.p_items[i].p_items[m].score
                      ).toFixed(5),
                      sname: getData.p_items[i].name,
                      symbol:
                        parseFloat(getData.p_items[i].p_items[m].score) > 1
                          ? parseFloat(getData.p_items[i].p_items[m].score) > 5
                            ? imgsRedBig
                            : imgsRedLittle
                          : parseFloat(getData.p_items[i].p_items[m].score) < 2
                          ? imgsBlueBig
                          : imgsBlueLittle,
                    };
                    list.push(listItem1);
                  }
                }
              }
            }
            var newLinkArr = [];
            this.chartData = list;
            if (this.chartData.length > 0) {
              for (var i = 0; i < this.chartData.length; i++) {
                // 清除风险为0的数据
                if (
                  parseFloat(this.chartData[i].proportion) <= 0 &&
                  this.chartData[i].sname !== this.chartData[i].name
                  // && this.chartData.length > 5
                ) {
                  this.chartData.splice(i, 1);
                  i--;
                }
              }
              for (let i = 0; i < this.chartData.length; i++) {
                newLinkArr.push(this.chartData[i]);
              }

              if (newLinkArr.length > 0) {
                let initI = 0;
                newLinkArr.length === 1 ? (initI = 0) : (initI = 1);
                for (var i = initI; i < newLinkArr.length; i++) {
                  var obj = {
                    source: newLinkArr[i].sname,
                    target: newLinkArr[i].name, //指向点
                    symbol: ["none", "arrow"],
                  };
                  this.chartLinks.push(obj);
                }
              }
            }
            this.analysisChart.hideLoading();

          } 
          else {
            this.hasSomeThing = true;
            this.analysisChart.hideLoading();
          }
          //待处理
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //风险分析tree
    creatAnalysis() {
      var that = this;
      this.renderAnalysisChart();
      this.analysisChart.hideLoading();
      this.analysisChart.on("click", function(params) {
        if (params.dataType === "node") {
          let addData = [];
          for (let i = 0; i < that.chartData.length; i++) {
            if (that.chartData[i].name === params.name) {
              let obj = JSON.parse(JSON.stringify(that.chartData[i]));
              obj.name = that.chartData[i].sname;
              addData.push(obj);
            }
          }
          that.chartData = [...that.chartData, ...addData];
          let beforeLen = JSON.parse(JSON.stringify(that.chartData2)).length;
          that.chartData2 = JSON.parse(JSON.stringify(that.chartData));
          for (let i = 0; i < that.chartData2.length; i++) {
            for (let j = i + 1; j < that.chartData2.length; j++)
              if (that.chartData2[i].name == that.chartData2[j].name) {
                that.chartData2.splice(j, 1);
                j--;
              }
          }
          let afterLen = JSON.parse(JSON.stringify(that.chartData2)).length;
          // 根据前后变化的数组长度判断是否有新展开的节点
          if (beforeLen === afterLen) {
            that.$message.error("暂无深入信息");
            return;
          }
          that.renderAnalysisChart();
        }
      });
    },
    renderAnalysisChart() {
      let option = {
        tooltip: {
          trigger: "item",
          formatter: function(params) {
            if (params.data.source && params.data.target) {
              return `${params.name}`;
            }
            var pattern = /^.*[1-9]+.*$/,
              deleteBrackets = /\{|}/g;
            var message = "风险分析";
            if (pattern.test(params.data.entcoremambers_dict)) {
              let datas = params.data.entcoremambers_dict.replace(
                deleteBrackets,
                ""
              );
              let texts = "";
              if (datas.indexOf(",") != -1) {
                datas = datas.split(",");
                datas.forEach((item) => {
                  if (pattern.test(item)) texts += item + " ";
                });
              } else {
                texts = datas;
              }
              message = message + "<br/>核心人失信：" + texts;
            }
            if (pattern.test(params.data.execution)) {
              let datas = params.data.execution.replace(deleteBrackets, "");
              let texts = "";
              if (datas.indexOf(",") != -1) {
                datas = datas.split(",");
                datas.forEach((item) => {
                  if (pattern.test(item)) texts += item + " ";
                });
              } else {
                texts = datas;
              }
              message = message + "<br/>企业失信：" + texts;
            }
            if (pattern.test(params.data.overduetax)) {
              let datas = params.data.overduetax.replace(deleteBrackets, "");
              let texts = "";
              if (datas.indexOf(",") != -1) {
                datas = datas.split(",");
                datas.forEach((item) => {
                  if (pattern.test(item)) texts += item + " ";
                });
              } else {
                texts = datas;
              }
              message = message + "<br/>历史欠税：" + texts;
            }
            if (pattern.test(params.data.case_mes)) {
              let datas = params.data.case_mes.replace(deleteBrackets, "");
              let texts = "";
              if (datas.indexOf(",") != -1) {
                datas = datas.split(",");
                datas.forEach((item) => {
                  if (pattern.test(item)) texts += item + " ";
                });
              } else {
                texts = datas;
              }
              message = message + "<br/>违法违规：" + texts;
            }
            if (pattern.test(params.data.equityqualities)) {
              let datas = params.data.equityqualities.replace(
                deleteBrackets,
                ""
              );
              let texts = "";
              if (datas.indexOf(",") != -1) {
                datas = datas.split(",");
                datas.forEach((item) => {
                  if (pattern.test(item)) texts += item + " ";
                });
              } else {
                texts = datas;
              }
              message = message + "<br/>股权出资：" + texts;
            }
            if (pattern.test(params.data.judicialfreeze)) {
              let datas = params.data.judicialfreeze.replace(
                deleteBrackets,
                ""
              );
              let texts = "";
              if (datas.indexOf(",") != -1) {
                datas = datas.split(",");
                datas.forEach((item) => {
                  if (pattern.test(item)) texts += item + " ";
                });
              } else {
                texts = datas;
              }
              message = message + "<br/>股权冻结：" + texts + " ";
            }
            if (pattern.test(params.data.auctions)) {
              let datas = params.data.auctions.replace(deleteBrackets, "");
              let texts = "";
              if (datas.indexOf(",") != -1) {
                datas = datas.split(",");
                datas.forEach((item) => {
                  if (pattern.test(item)) texts += item + " ";
                });
              } else {
                texts = datas;
              }
              message = message + "<br/>司法拍卖：" + texts;
            }
            if (
              params.data.business_error &&
              params.data.business_error !== "-"
            ) {
              let datas = params.data.business_error.replace(
                deleteBrackets,
                ""
              );
              let texts = "";
              if (datas.indexOf(",") != -1) {
                datas = datas.split(",");
                datas.forEach((item) => {
                  if (pattern.test(item)) texts += item + " ";
                });
              } else {
                texts = datas;
              }
              message = message + "<br/>" + texts;
            }
            return message + "<br/>风险评分：" + params.data.proportion;
          },
          extraCssText:
            "padding:10px 15px;background:#fff;box-shadow:0 0 10px rgba(3,179,140,1);color:#7674a3;border-radius:3px;",
        },
        series: [
          {
            type: "graph",
            layout: "force",
            roam: true,
            nodeScaleRatio: 0.6,
            itemStyle: {
              //连接线样式
              normal: {
                label: { show: true },
                color: "#03b38c", //圆球颜色
                lineStyle: {
                  width: 1,
                  opacity: 1,
                  color: "#4fc9ae",
                  type: "dashed", //'dotted或dashed'虚线 'solid'实线
                },
              },
            },
            label: {
              normal: {
                //节点标题样式
                show: true,
                position: ["30%", "120%"], //设置label显示的位置
                textStyle: {
                  fontSize: 14,
                  color: "#03b38c",
                },
              },
            },
            symbolSize: (value, params) => {
              //   根据数据params中的data来判定数据大小
              if (params.data.category == 0) {
                return 100;
              } else {
                if (params.data.proportion > 2) {
                  //有风险
                  if (params.data.proportion > 5) {
                    return 55;
                  } else {
                    return 28;
                  }
                } else {
                  //无风险
                  if (params.data.proportion > 1) {
                    return 28;
                  } else {
                    return 55;
                  }
                }
              }
            },
            draggable: true,
            data: this.chartData2,
            force: {
              edgeLength: [100, 230],
              repulsion: 200, //节点之间的斥力因子。
              gravity: 0.02, //节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
              layoutAnimation: true,
            },
            links: this.chartLinks,
          },
        ],
      };
      this.analysisChart.setOption(option);
    },
  },
  watch: {
    chartLinks: function(value) {
      if (value.length > 0) {
        // 翻转父名称
        for (let i = 0; i < this.chartData.length; i++) {
          if (this.chartData[i].isFather == true) {
            let medium = this.chartData[i].name;
            this.chartData[i].name = this.chartData[i].sname;
            this.chartData[i].sname = medium;
          }
        }
        // 去重
        this.chartData2 = JSON.parse(JSON.stringify(this.chartData));
        for (let i = 0; i < this.chartData2.length; i++) {
          for (let j = i + 1; j < this.chartData2.length; j++)
            if (this.chartData2[i].name == this.chartData2[j].name) {
              this.chartData2.splice(j, 1);
              j--;
            }
        }
        this.creatAnalysis();
      }
    },
    "$i18n.locale"() {
      this.tips = [
        this.$t("assessment.RiskyCompanies"),
        this.$t("assessment.RiskFreeCompanies"),
      ];
    },
  },
  mounted() {
    this.init();
    this.getAnalysis();
  },
};
</script>

<style lang="scss" scoped>
.analysis {
  padding: 1px 0 25px;
  background-color: #fff;
  border-radius: 10px;
}
.infoTitle {
  padding-left: 25px;
  margin: 32px 0;
  font-size: 14px;
  color: $mainColor;
  font-weight: bold;
  border-left: 5px solid $mainColor;
}
.analysisChart {
  height: 650px;
}
.body {
  position: relative;
}
.tips {
  position: absolute;
  top: 0;
  left: 20px;
  display: flex;
  flex-wrap: nowrap;
}
.tips > span {
  margin-right: 45px;
  padding-left: 22px;
  font-size: 12px;
  color: #fc3f4d;
  background: url("../img/risk01.png") no-repeat left center;
}
.tips > span:last-of-type {
  background-image: url("../img/risk02.png");
  color: $mainColor;
}
.analysisBox {
  position: relative;
}
.nothing {
  display: none;
  text-align: center;
  padding-top: 100px;
  font-size: 15px;
  color: #666;
}
.nothing.show {
  display: block;
  position: absolute;
  width: 100%;
  top: 100px;
  left: 0;
}
</style>
